<template>

    <div>
        <el-button type="danger" :icon="Plus" style="float: left;;margin-left: 10px;"
            @click="result">新增</el-button>&emsp;
        <el-button type="danger" :icon="Check" style="float: left;;margin-left: 10px;"
            @click="save()">保存</el-button>&emsp;
        <el-button type="danger" :icon="Back" style="float: left;;margin-left: 10px;"
            @click="delDomain()">撤销</el-button>&emsp;
        <el-button type="danger" :icon="Delete" style="float: left;;margin-left: 10px;"
            @click="DeleteLoge()">删除</el-button>
    </div>
    <br />
    <div>
        <span style="font-weight: bold;"> 销售日期:</span>&emsp;
        <el-date-picker v-model="form.salesDate" type="date" style="width: 200px;border: none;"
            placeholder="日期" />&emsp;&emsp;
        <span style="font-weight: bold;"> 客户: </span>&emsp;
        <el-input style="width: 200px;" v-model="form.customer" placeholder="-- --" />&emsp;&emsp;
        <span style="font-weight: bold;"> 销售员: </span>&emsp;
        <el-select v-model="form.salesPerson" placeholder="Select" size="large" style="width: 240px">
            <el-option label="罗翔" value="罗翔" />
            <el-option label="扬家霖" value="扬家霖" />
            <el-option label="雷鑫" value="雷鑫" />
            <el-option label="王单青" value="王单青" />
            <el-option label="温暖暖" value="温暖暖" />
            <el-option label="杨杰" value="杨杰" />
            <el-option label="赵丽" value="赵丽" />
            <el-option label="黄强" value="黄强" />
            <el-option label="吴敏" value="吴敏" />
            <el-option label="周亮" value="周亮" />
            <el-option label="徐蕾" value="徐蕾" />
            <el-option label="孙伟" value="孙伟" />
            <el-option label="李霞" value="李霞" />
            <el-option label="马超" value="马超" />
            <el-option label="郭丽" value="郭丽" />
            <el-option label="高峰" value="高峰" />
            <el-option label="何敏" value="何敏" />
            <el-option label="林静" value="林静" />
            <el-option label="罗文" value="罗文" />
            <el-option label="蒋娜" value="蒋娜" />
        </el-select>
        <el-form-item label="部门" prop="department">
            <el-cascader v-model="value" :props="props" :options="options2" @change="handleChange2" />
        </el-form-item>
        <span style="font-weight: bold;"> 仓库: </span>&emsp;
        <el-select v-model="form.warehouse" placeholder="Select" size="large" style="width: 240px">
            <el-option label="仓库1" value="仓库1" />
            <el-option label="仓库2" value="仓库2" />
        </el-select>
        <span style="font-weight: bold;"> 收货地址: </span>&emsp;
        <el-input style="width: 200px;" v-model="form.shippingAddress" placeholder="-- --" />
        <span style="font-weight: bold;"> 单据号: </span>&emsp;
        <el-input style="width: 200px;" v-model="form.documentNo" placeholder="-- --" />
        <span style="font-weight: bold;"> 流水号: </span>&emsp;
        <el-input style="width: 200px;" v-model="form.SerialNo" placeholder="-- --" />
    </div>
    <br />
    <hr style="font-size: 20px;" />
    <br />

    <div class="table-container" style=" height: 400px;position: relative;">
        <table style="border-collapse: collapse;">
            <tr>
                <td>序号</td>
                <td>耳号</td>
                <td>成交价（元）</td>
                <td>定价</td>
                <td>折扣比例</td>
                <td>等级</td>
                <td>品种</td>
                <td>性别</td>
                <td>羊只类型</td>
                <td>繁殖状态</td>
                <td>栋舍</td>
                <td>栏位</td>
                <td>出生日期</td>
                <td>出生重(kg)</td>
                <td>断奶重(kg)</td>
                <td>父耳号</td>
                <td>母耳号</td>
                <td>月龄</td>
            </tr>
            <tr v-for="(ruleForm, index) in loge.healthArray">
                <td>{{ index + 1 }}</td>
                <td>
                    <el-select style="width: 100px" v-model="ruleForm.earTag" placeholder="请选择">
                        <el-option v-for="item in eweData" :label="item.earNumber" :value="item.sleepInforId"
                            @click="getearMsg(index)" />
                    </el-select>
                </td>
                <td>
                    <el-input style="width: 100px" v-model="ruleForm.price"></el-input>
                </td>
                <td>
                    <el-input style="width: 100px" v-model="ruleForm.listPrice"></el-input>
                </td>
                <td>
                    <el-input style="width: 100px" v-model="ruleForm.discountRate"></el-input>
                </td>
                <td>
                    <el-select style="width: 100px" v-model="ruleForm.grade" placeholder="请选择">

                        <el-option label="特级" :value="1" />
                        <el-option label="1级" :value="2" />
                        <el-option label="2级" :value="3" />
                        <el-option label="3级" :value="4" />
                        <el-option label="4级" :value="5" />
                        <el-option label="5级" :value="6" />

                    </el-select>
                </td>
                <td>
                    <el-select style="width: 100px" v-model="ruleForm.breed" placeholder="请选择">
                        <el-option v-for="item in SearchVariety" :label="item.varietyName" :value="item.varietyId" />
                    </el-select>
                </td>
                <td>
                    <el-select style="width: 100px" v-model="ruleForm.gender" placeholder="请选择">
                        <el-option label="公" :value="1" />
                        <el-option label="母" :value="2" />
                    </el-select>
                </td>
                <td>
                    <el-select style="width: 100px" v-model="ruleForm.sheepType" placeholder="请选择">
                        <el-option label="种公" :value="1" />
                        <el-option label="种母" :value="2" />
                        <el-option label="后裔" :value="3" />
                    </el-select>
                </td>
                <td>
                    <el-select style="width: 100px" v-model="ruleForm.breedingStatus" placeholder="请选择">
                        <el-option label="空怀" :value="1" />
                        <el-option label="配种" :value="2" />
                        <el-option label="妊娠" :value="3" />
                        <el-option label="分娩" :value="4" />
                        <el-option label="哺乳" :value="5" />
                        <el-option label="断奶" :value="6" />
                    </el-select>
                </td>
                <td>
                    <el-select style="width: 100px" v-model="ruleForm.barn" placeholder="请选择">
                        <el-option v-for="item in Recordcottage" :label="item.cottageName" :value="item.cottagesId"
                            @click="getFields(ruleForm.barn)" />
                    </el-select>
                </td>
                <td>
                    <el-select style="width: 100px" v-model="ruleForm.stall" placeholder="请选择">
                        <el-option v-for="item in Fields" :label="item.fieIdName" :value="item.fieIdId" />
                    </el-select>
                </td>
                <td>
                    {{ ruleForm.birthDate }}
                </td>
                <td>
                    {{ ruleForm.birthWeight }}
                </td>
                <td>
                    {{ ruleForm.weaningWeight }}
                </td>
                <td>
                    {{ ruleForm.fatherId }}
                </td>
                <td>
                    {{ ruleForm.motherId }}
                </td>
                <td>
                    {{ ruleForm.ageInMonths }}
                </td>
            </tr>
        </table>

    </div>
    <div style="bottom: 0; left: 0;width: 100%;;">
        <hr>
        <!-- <span>&emsp; 合计</span>
            <hr> -->
        <el-button link type="danger" :icon="Plus" style="float: left;;margin-left: 10px;"
            @click="addDomain">增行</el-button>&emsp;
        <el-button link type="danger" :icon="Check" style="float: left;;margin-left: 10px;"
            @click="delDomain">删行</el-button>&emsp;
        <br />
        <hr>
        <span style="vertical-align: top;width: 5%;">&emsp; 备注</span>&emsp;
        <el-input v-model="form.message" type="textarea" style="width: 85%;" />
    </div>


</template>
<script lang="ts" setup>
import {
    Check,
    Delete,
    Plus,
    Back,
} from '@element-plus/icons-vue'
import { reactive, ref, onMounted, computed } from 'vue';
import axios from 'axios';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import type { ComponentSize, FormInstance, FormRules } from 'element-plus';
//调用持久化
import { useCounterStore } from '@/stores/counter';
const counterStore = useCounterStore();
const route = useRoute();
const router = useRouter();
const currentDate = new Date();

//钩子函数
onMounted(() => {
    getParturitionDifficulty()//分娩难易度
    getFatSheepBatch()//羔羊批次
    geteweData()//耳号
    getRecordcottage()//栋舍
    getserialNumber()//流水号
    getOptions2()
    aaaData()
    getSearchVariety()
})
const loge = reactive({
    healthArray: <any>[
        reactive({
            "createId": counterStore.employeeId,
            "createTime": new Date(),
            updateId: null,
            updateTime: null,
            deleteId: null,
            deletes: false,
            deleteTime: null,
            examId: null,
            examTime: null,
            "salesRecordId": 0,
            "salesDate": null,
            "customer": "",
            "salesPerson": "",
            "department": 0,
            "warehouse": "",
            "shippingAddress": "",
            "documentNumber": '',
            "serialNumber": '',
            "earTag": '',
            "price": '',
            "listPrice": '',
            "discountRate": '',
            "grade": '',
            "breed": '',
            "gender": '',
            "sheepType": '',
            "breedingStatus": '',
            "barn": '',
            "stall": '',
            "birthDate": null,
            "birthWeight": '',
            "weaningWeight": '',
            "fatherId": "",
            "motherId": "",
            "ageInMonths": "",
            "remarks": '',
        })
    ],
});

//增行
const addDomain = () => {
    loge.healthArray.push(
        reactive({
            "createId": counterStore.employeeId,
            "createTime": new Date(),
            updateId: null,
            updateTime: null,
            deleteId: null,
            deletes: false,
            deleteTime: null,
            examId: null,
            examTime: null,
            "salesRecordId": 0,
            "salesDate": null,
            "customer": form.customer,
            "salesPerson": form.salesPerson,
            "department": form.department,
            "warehouse": form.warehouse,
            "shippingAddress": form.shippingAddress,
            "documentNumber": form.documentNo,
            "serialNumber": form.SerialNo.toString(),
            "earTag": "",
            "price": "",
            "listPrice": "",
            "discountRate": "",
            "grade": "",
            "breed": "",
            "gender": "",
            "sheepType": "",
            "breedingStatus": "",
            "barn": "",
            "stall": "",
            "birthDate": null,
            "birthWeight": "",
            "weaningWeight": "",
            "fatherId": "",
            "motherId": "",
            "ageInMonths": '',
            "remarks": form.message,

        }));
    console.log(loge.healthArray);
};

//新增 
const result = () => {
    loge.healthArray = []
    addDomain();
}
const DeleteLoge = () => {
    loge.healthArray = []
}


//减行撤销
const delDomain = () => {
    loge.healthArray.splice(loge.healthArray.length - 1, 1)
}

//获取羊只信息
const form = reactive({
    salesDate: "",//日期
    message: '',//备注
    customer: '',//客户
    salesPerson: '',//销售员
    warehouse: '',//仓库
    shippingAddress: '',//收货地址 
    department: '',//部门
    documentNo: '',//单据号
    SerialNo: '',//流水号

})
const aaaData = () => {
    let n = new Date();
    // 获取年、月、日
    let year = n.getFullYear();
    let month = (n.getMonth() + 1).toString().padStart(2, '0'); // 月份是从0开始的，所以需要 +1
    let day = n.getDate().toString().padStart(2, '0'); // 保证天数是两位数
    // 拼接成 "YYYYMMDD" 格式
    let dateString = `${year}${month}${day}`;
    form.documentNo = dateString;
}

//#region 级联部门
//部门级联

const value = ref([])
const props = {
    expandTrigger: 'hover' as const,
}

const handleChange2 = (value: any) => {
    form.department = value[value.length - 1]
    console.log(form.department)

}
const options2 = ref([])
const getOptions2 = () => {
    axios.get("http://localhost:5039/api/Depart/SearchDepartmentTree").then((res) => {
        console.log(res.data.data)
        options2.value = res.data.data
    })
}


//#endregion

/*------------下拉框------------*/
//#region
// 品种下拉框
const SearchVariety = ref<any>([])
const getSearchVariety = () => {
    axios.get('http://localhost:5039/api/SleepBegin/SearchVariety').then(res => {
        SearchVariety.value = res.data.data;
    })
}

const ParturitionDifficulty = ref<any>([]);//获取分娩难易度
const getParturitionDifficulty = () => {
    axios.get('http://localhost:5039/api/ProductionManagement/ParturitionDifficultyList').then(res => {
        ParturitionDifficulty.value = res.data.data;
    })
}

const FatSheepBatch = ref<any>([]);//获取肥羊品种
const getFatSheepBatch = () => {
    axios.get('http://localhost:5039/api/ProductionManagement/FatSheepBatchList').then(res => {
        FatSheepBatch.value = res.data.data;
    })
}


const eweData = ref<any>([]);//获取耳号
const geteweData = () => {
    axios.get('http://localhost:5039/api/SleepBegin/SelectEarFeMale').then(res => {
        eweData.value = res.data.data;
    })
}

const Recordcottage = ref<any>([]);//获取栋舍 
const getRecordcottage = () => {
    axios.post('http://localhost:5039/api/Cottages/CottageList', {
    }).then(res => {
        Recordcottage.value = res.data.data;
    })
}

const Fields = ref<any>([]);//获取栏位 
const getFields = (id: number) => {
    console.log(id);
    axios.post('http://localhost:5039/api/Cottages/SearchFields', {
        "cottagesId": id,
        "pageIndex": 1,
        "pageSize": 100000000
    }).then(res => {
        console.log(res.data.data);
        Fields.value = res.data.data;
    })
}
//获取羊只信息
const updates = reactive({
    EweID: '',
    Gender: '',//性别
    CurrentBarn: '',
    CurrentPen: '',
    breedStatuId: '',//状态
    grade: '',//等级
    breed: '',//品种
    sheepType: '',//养只类型
    breedingStatus: '',//羊只状态
    barn: '',//栋舍
    stall: '',//栏位
    birthDate: '',//出生日期
    birthWeight: '',//出生重
    weaningWeight: '',//断奶重
    motherId: '',//母号
    fatherId: '',//父号
    ageInMonths: '',//月龄

})

//#region 耳号反填

//通过耳号和状态获取妊娠 的信息
const getearMsg = (index: any) => {
    const selectedEweID = loge.healthArray[index].earTag; // 获取选中的 EweID
    console.log(selectedEweID);
    axios.get('http://localhost:5039/api/ProductionManagement/EarMasList', {
        params: {
            SleepInforId: selectedEweID,
        }
    }).then(res => {
        console.log(res.data.item);
        updates.EweID = res.data.item.sleepInforId;
        updates.Gender = res.data.item.gender;
        updates.breedStatuId = res.data.item.breedStatuId;
        updates.grade = res.data.item.gradeId;
        updates.breed = res.data.item.varietyId;
        updates.sheepType = res.data.item.sleepTypeId;
        updates.breedingStatus = res.data.item.breedStatuId;
        updates.barn = res.data.item.recordcottageId;
        updates.stall = res.data.item.fieIdId;
        updates.birthDate = res.data.item.sleepBirthDate;
        updates.birthWeight = res.data.item.sleepBirthWeight;
        updates.weaningWeight = res.data.item.weanWeight;
        updates.motherId = res.data.item.moEarNumber;
        updates.fatherId = res.data.item.farEarNumber;
        updates.ageInMonths = res.data.item.ageDay;
        handleUpdate()//调用更新数据的方法
    })

}
// 例子：通过表单输入更新数据
const handleUpdate = () => {
    const data = {
        eweID: updates.EweID, // 假设你从表单获取到的 EweID
        gender: updates.Gender, // 假设你从表单获取到的 Gender 
        breedStatuId: updates.breedStatuId,//状态
        grade: updates.grade,//等级
        breed: updates.breed,//品种
        sheepType: updates.sheepType,//养只类型
        breedingStatus: updates.breedingStatus,//羊只状态
        barn: updates.barn,//栋舍
        stall: updates.stall,//栏位
        birthDate: updates.birthDate,//出生日期
        birthWeight: updates.birthWeight,//出生重
        weaningWeight: updates.weaningWeight,//断奶重
        motherId: updates.motherId,//母号
        fatherId: updates.fatherId,//父号
        ageDay: updates.ageInMonths//月龄
    }
    console.log(data)
    updateFieldsByEweID(data);
};
const updateFieldsByEweID = (data: any) => {
    // 遍历 healthArray 找到 EweID 对应的项并更新
    const healthItem = loge.healthArray.find((item: any) => item.earTag === data.eweID);

    if (healthItem) {
        healthItem.earTag = data.eweID;
        healthItem.gender = data.gender;
        healthItem.breedStatuId = data.breedStatuId;
        healthItem.grade = data.grade;
        healthItem.breed = data.breed;
        healthItem.sheepType = data.sheepType;
        healthItem.breedingStatus = data.breedingStatus;
        healthItem.barn = data.barn;
        getFields(healthItem.barn)
        healthItem.stall = data.stall;
        healthItem.birthDate = data.birthDate;
        healthItem.birthWeight = data.birthWeight;
        healthItem.weaningWeight = data.weaningWeight;
        healthItem.motherId = data.motherId;
        healthItem.fatherId = data.fatherId;
        healthItem.ageInMonths = data.ageDay.toString();



    } else {
        console.log(`没有找到EweID为 ${data.eweID} 的数据`);
    }
};
/*------------流水号------------*/
const getserialNumber = () => {
    axios.post('http://localhost:5039/api/ProductionManagement/GetId', {}).then(res => {
        form.SerialNo = res.data;
    })
}

//#endregionsalesDate



//#region 保存
const save = () => {
    console.log(form.customer.trim())
    var s = form.salesDate
    // if (s.toString().trim() === '') {
    //     ElMessage.error("请补全转种日期");
    //     return;
    // }
    // if (form.customer.trim() === '') {
    //     ElMessage.error("请补客户");
    //     return;
    // }
    // if (form.salesPerson.trim() === '') {
    //     ElMessage.error("请补全销售员");
    //     return;
    // }
    // if (form.department === '') {
    //     ElMessage.error("请补全部门");
    // }
    // if (form.shippingAddress === '') {
    //     ElMessage.error("请补全地址");
    //     return;
    // }
    // if (form.warehouse == "0") {
    //     ElMessage.error("请补全仓库");
    //     return;
    // }
    // if (form.message === '') {
    //     ElMessage.error("请补全备注");
    //     return;
    // }

    console.log(loge.healthArray)
    loge.healthArray.forEach((item: any) => {
        item.remarks = form.message,//备注
            item.documentNumber = form.documentNo,//单据编号
            item.serialNumber = form.SerialNo.toString(),//流水号 
            item.shippingAddress = form.shippingAddress,//收货地址
            item.warehouse = form.warehouse,//仓库
            item.customer = form.customer,//客户
            item.salesPerson = form.salesPerson,//销售员
            item.department = form.department,//部门
            console.log(JSON.stringify(form.salesDate))
        // item.salesDate = JSON.stringify(form.salesDate)//  
        item.salesDate = form.salesDate
    })
    let obj = {
        salesRecord: loge.healthArray
    }
    axios.post('http://localhost:5039/api/Sales_Purchases/BreedingSalesCreate', obj).then(res => {
        if (res.data.code == 0) {
            console.log('保存成功');
            router.push('/BreedingSalesListView')
        }
    })
}


//#endregion

// const ageInMonths = computed(() => {
//     const birth = new Date(updates.BirthDate);
//     let ageMonths = (currentDate.getFullYear() - birth.getFullYear()) * 12;
//     ageMonths -= birth.getMonth();
//     ageMonths += currentDate.getMonth();
//     if (currentDate.getDate() < birth.getDate()) {
//         ageMonths--;
//     }
//     return ageMonths;
// });
</script>



<style scoped>
.demo-pagination-block+.demo-pagination-block {
    margin-top: 10px;
}

.demo-pagination-block .demonstration {
    margin-bottom: 16px;
}

/* 设置第一行的 td 顶部边框加粗并设置为红色 */
table tr:first-child td {
    border-top: 3px solid red;
    /* 设置顶部边框为3px宽度的红色 */
    padding: 10px;
    text-align: center;
}

/* 设置 td 的样式 */

table td {
    padding: 10px;
    border: 1px solid #ccc;
    text-align: center;
    font-size: 14px;
    height: 60px;
    width: 150px;
    white-space: nowrap;
    /* 防止内容换行 */
}

/* 可选：为 table 添加样式 */
table {
    width: 100%;
    border-collapse: collapse;
    table-layout: fixed;
}



/*______________________________________________________*/

.table-container {
    max-width: 100%;
    overflow-x: auto;
    /* 启用水平滚动 */
    margin: 20px 0;
    /* 设置容器的外边距 */
}

:deep(.el-input__wrapper) {
    box-shadow: none;
    text-align: center;
}

:deep(.el-select__wrapper) {
    box-shadow: none;
}

::v-deep(.center-input .el-input__inner) {
    text-align: center;
}
</style>